﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using EP.Base.BaseService.Manager.Interface.Business;

namespace EP.Base.BaseService.Manager.Business
{
    /// <summary>
    /// 正则提取索引时间
    /// </summary>
    public class IndexDateExtract : IIndexDateExtract
    {
        public Dictionary<string, DateTime> Extract(string regStr, IEnumerable<string> indexNames)
        {
            var enumerable = indexNames as string[] ?? indexNames.ToArray();
            if (indexNames == null || !enumerable.Any())
                return null;
            var reg = new Regex(regStr);
            var result= enumerable.ToDictionary(indexName => indexName, indexName => RegGetDate(reg, indexName));

            return result;
        }

        private DateTime RegGetDate(string regStr,string indexName)
        {
            var reg = new Regex(regStr);
            MatchCollection mc = reg.Matches(indexName);
            return RegGetDate(reg, indexName);
        }
        private DateTime RegGetDate(Regex reg, string indexName)
        {
            MatchCollection mc = reg.Matches(indexName);
            int year = 1754;
            int month = 1;
            int day = 1;
            foreach (Match m in mc)
            {
                if (m.Groups["year"] != null)
                    int.TryParse(m.Groups["year"].ToString(), out year);

                if (m.Groups["month"] != null)
                    int.TryParse(m.Groups["month"].ToString(), out month);

                if (m.Groups["day"] != null)
                    int.TryParse(m.Groups["day"].ToString(), out day);
            }
            year = year <= 0 ? 1 : year;
            month = month <= 0 ? 1 : month;
            day = day <= 0 ? 1 : day;
            return new DateTime(year,month,day);
        }
    }
}
